#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanXinyangPolicy(BaseTaxPolicySpider):
    name = 'henan_xinyang_8888_policy'
    
    province = '河南省'
    city = '信阳市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url, path in [
            ['信阳市商城县人民政府', '商城县', 'http://www.hnsc.gov.cn/public/column/6596321?type=4&action=list&nav=&sub=&catId=6719691', '首页>政府信息公开>政策>规范性文件'],
            ['信阳市商城县人民政府', '商城县', 'http://www.hnsc.gov.cn/public/column/6596321?type=4&action=list&nav=&sub=&catId=6716901', '首页>政府信息公开>政策>商政文件'],
            ['信阳市商城县人民政府', '商城县', 'http://www.hnsc.gov.cn/public/column/6596321?type=4&action=list&nav=&sub=&catId=6716911', '首页>政府信息公开>政策>商政办文件'],
            ['信阳市商城县工业和信息化局', '商城县', 'http://www.hnsc.gov.cn/public/column/6596381?type=4&action=list', '首页>政务公开>政府信息公开>法定主动公开内容>部门文件'],
            ['信阳市商城县人力资源和社会保障局', '商城县', 'http://www.hnsc.gov.cn/public/column/6596441?type=4&action=list&nav=3&catId=6717801', '首页>政务公开>政府信息公开>法定主动公开内容>部门文件'],
            ['信阳市商城县文化广电和旅游局', '商城县', 'http://www.hnsc.gov.cn/public/column/6596501?type=4&action=list', '首页>政务公开>政府信息公开>法定主动公开内容>部门文件'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={"item": item, "path": path}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        topic = response.meta['path'].split('>')[-1]
        organId = response.url.split("?")[0].split("/")[-1]
        catId = response.url.split("&catId=")
        if len(catId) == 2:
            catId = catId[1]
        else:
            catId = '$catId'
        url = response.xpath('.').re_first(r'url:\s*"(.*?site/label/8888)"') or '/site/label/8888'
        siteId = response.xpath('.').re_first(r'siteId\s*:\s*"(\d+)"')
        params = {
            "_": "0.30172634147269317",
            "labelName": "publicInfoList",
            "siteId": siteId,
            "organId": str(organId),
            "pageSize": "15",
            "catId": catId,
            "type": "4",
            "length": "80",
            "file": "/shangcheng/xxgk/publicInfoList_newest"
        }
        yield response.follow(url + '?' + urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//ul[@class='pageTPList' or @class='infoList']/li//a[@title]/ancestor::li[string-length(string(.))>=10] |"
            "//tr[@class='xxgk_nav_con']/td//a[@title]/ancestor::td[string-length(string(.))>=10] |"
            "//li[@class='clearfix']//a[@class]/ancestor::li[string-length(string(.))>=5]"
        )
        # if not elem_list:
        #     yield response.follow(response.url, callback=self.parse_list, meta=response.meta, dont_filter=True)
        #     return
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.pdf' in item['source_url'] or '.doc' in item['source_url']:
                continue
            else:
                print(response.url, item['source_url'])
                yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath(""".""").re_first(r"""pageCount\s*:\s*[\(]?(\d+)\s*""")
            if not total_page:
                print(total_page, response.text)
            print(response.url, "page:", total_page)
            for page_num in range(2, int(total_page) + 1):
                yield response.follow(response.url + f'&pageIndex={page_num}',
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False}, dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_xinyang_8888_policy".split())
